package com.spukmk3me.io;

import java.io.IOException;
import java.io.InputStream;

import com.spukmk3me.util.DoublyLinkedList;

public abstract class FileSystem
{
    protected FileSystem()
    {
        m_handleList = new DoublyLinkedList();
    }
    
    public final FileHandle createFileHandle( String path, byte location )
    {
        DoublyLinkedList.Iterator i = m_handleList.first();
        DoublyLinkedList.Iterator e = m_handleList.end();
        FileHandle handle = null;
        boolean found = false;
        
        for ( ; !i.equals( e ); i.fwrd() )
        {
            handle = (FileHandle)i.data();
            
            if ( location == handle.getLocation() )
            {
                if ( path.equals( handle.getPath() ) )
                {
                    found = true;
                    break;
                }
            }
        }
        
        if ( found )
            return handle;
        else
        {
            handle = _createFileHandle( path, location );
            
            if ( handle.exists() )
            {
                handle.inc();
                m_handleList.push_back( handle );
                return handle;
            }
            
            return null;
        }
    }
    
    public final void clearUnusedHandles()
    {
        DoublyLinkedList.Iterator i = m_handleList.first();
        DoublyLinkedList.Iterator e = m_handleList.end();
        FileHandle handle = null;
        
        for ( ; !i.equals( e ); )
        {
            handle = (FileHandle)i.data();
            i.fwrd();
            
            if ( handle.getCounter() == 1 )
                m_handleList.erase( handle );
        }
    }
    
    protected abstract FileHandle _createFileHandle( String path, byte location );
    
    private DoublyLinkedList m_handleList;
}
